package com.action;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.model.User;
import com.service.UserService;
import com.service.impl.UserServiceImpl;

@WebServlet("/UserController")
public class UserController extends HttpServlet {
	private static final long serialVersionUID = 1L;

	public UserController() {
		super();
		// TODO Auto-generated constructor stub
	}

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(request, response);

	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String method = request.getParameter("method");
		if ("login".equals(method)) {
			login(request, response);
		} else if ("logout".equals(method)) {
			logout(request, response);
		} else {
			response.getWriter().write(
					"{\"success\":true,\"msg\":\"用户名或密码有错！\"}");
			response.getWriter().flush();
		}
	}

	protected void login(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub

		String username = request.getParameter("username");
		String password = request.getParameter("password");

		System.out.println("<debug>" + username + " " + password);

		UserService userService = new UserServiceImpl();
		User user = userService.validateUser(username, password);

		System.out.println("<debug>" + user);

		String resultJson;
		if (user != null) {
			HttpSession session = request.getSession();
			session.setAttribute("User", user);
			resultJson = "{\"success\":true,\"msg\":\"登录成功！\",\"url\":\"main.jsp\"}";
		} else {
			resultJson = "{\"success\":true,\"msg\":\"登录失败！\",\"url\":\"index.jsp\"}";
		}
		response.getWriter().write(resultJson);
		response.getWriter().flush();
	}

	protected void logout(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		HttpSession session = request.getSession(false);
		if (session == null || session.getAttribute("User") != null) {
			session.removeAttribute("User");
		}
		response.sendRedirect("index.jsp");
	}
}
